//
//  LZGrabCouponDetailPopView.m
//  laziz_Consumer
//
//  Created by xbnzd on 17/4/13.
//  Copyright © 2017年 XBN. All rights reserved.
//

#import "LZGrabCouponDetailPopView.h"
#import "LZGrabCouponAndFightGroupsDetialModel.h"
#import "extobjc.h"
#import "Masonry.h"

#import "LZVideoActivityView.h"
#import "LZLanguageManager.h"

#import "LZGrabCouponPopScrollView.h"


@interface LZGrabCouponDetailPopView  ()<UIGestureRecognizerDelegate,LZGrabCouponPopScrollViewDelegate,CAAnimationDelegate>

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UIView *shadowBgView;
@property (nonatomic, strong) UIImageView *topImgView;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) LZVideoActivityView *activityView;
@property (nonatomic, strong) LZGrabCouponPopScrollView *scrollView;
@end

@implementation LZGrabCouponDetailPopView
- (instancetype)init
{
    self = [super init];
    
    if (self) {
        
        [self configureUI];
        
        [self setSubviewMasonry];
        
    }
    
    return self;
}


#pragma mark - UI
- (void)configureUI
{
    GET_SCREEN_SCALE(scale);
    self.backgroundColor = UIColorFromRGB(0x111111, 0);
    self.bgView.layer.cornerRadius = 6;
    self.bgView.layer.masksToBounds = YES;
    
    self.shadowBgView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.shadowBgView.layer.shadowOffset = CGSizeMake(3,4);
    self.shadowBgView.layer.shadowOpacity = 0.5;
    self.shadowBgView.layer.shadowRadius = 4;
    
    self.scrollView.contentInset = UIEdgeInsetsMake(148*scale, 0, 0, 0);
    
    [self addSubview:self.shadowBgView];
    [self.shadowBgView addSubview:self.bgView];
    [self.bgView addSubview:self.topImgView];
    [self.bgView addSubview:self.activityView];
    [self.bgView addSubview:self.scrollView];
    [self.shadowBgView addSubview:self.cancelBtn];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelSelfWithAnimation)];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
    
}

- (void)setSubviewMasonry
{
    GET_SCREEN_SCALE(scale);
    
    [self.shadowBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(CGPointMake(0, 0));
        make.width.mas_equalTo(275*scale);
        make.height.mas_equalTo(348*scale);
    }];
    
    self.shadowBgView.transform = CGAffineTransformMakeScale(0.01, 0.01);
    self.shadowBgView.hidden = YES;
    
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [self.topImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.trailing.mas_equalTo(0);
        make.height.mas_equalTo(148*scale);
    }];
    
    [self.activityView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 40));
        make.top.equalTo(self.topImgView.mas_bottom).offset(20);
        make.centerX.equalTo(self.activityView.superview);
    }];
    
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    

    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 50));
        make.leading.equalTo(self.bgView.mas_trailing).offset(-30);
        make.top.equalTo(self.bgView.mas_top).offset(-20);
    }];
}


#pragma mark - private

- (void)setDetailModel:(LZGrabCouponAndFightGroupsDetialModel *)detailModel
{
    _detailModel = detailModel;
    [self.activityView stopActivity];
    self.scrollView.detailModel = detailModel;
}
- (void)setAnimationBeginPoint:(CGPoint)animationBeginPoint
{
    _animationBeginPoint = animationBeginPoint;
    [self.shadowBgView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(CGPointMake(animationBeginPoint.x-self.center.x, animationBeginPoint.y-self.center.y));
    }];
    [self layoutIfNeeded];
}
- (void)setButtonsUserInteractionEnabled:(BOOL)userInteractionEnabled
{
    [self.scrollView setUserInteractionEnabled:userInteractionEnabled];
}

- (void)showSelfAnimation
{
    [self.activityView startActivityForWaitSomeSecond:1];
    self.scrollView.contentSize = CGSizeMake(0, 0);
    
    @weakify(self);
    [UIView animateWithDuration:0.25 animations:^{
        @strongify(self);
        self.backgroundColor = UIColorFromRGB(0x111111, 0.7);
    } completion:^(BOOL finished) {
    }];
    
    if (self.shadowBgView.hidden == YES) {
        self.shadowBgView.hidden = NO;
    }
    
    [self.shadowBgView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.and.centerY.equalTo(self);
    }];
    [self setNeedsUpdateConstraints];
    [self updateConstraintsIfNeeded];
 
    [UIView animateWithDuration:.55 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        @strongify(self);
        [self layoutIfNeeded];
        self.shadowBgView.transform = CGAffineTransformMakeScale(1.0, 1.0);
    } completion:^(BOOL finished) {

    }];

}

- (void)cancelSelfWithAnimation
{
    @weakify(self);
    [self.shadowBgView mas_updateConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.center.mas_equalTo(CGPointMake(self.animationBeginPoint.x-self.center.x, self.animationBeginPoint.y-self.center.y));
    }];
    [self setNeedsUpdateConstraints];
    [self updateConstraintsIfNeeded];
    
    [UIView animateWithDuration:0.25 animations:^{
        @strongify(self);
        [self layoutIfNeeded];
        self.backgroundColor = UIColorFromRGB(0x111111, 0);
        self.shadowBgView.transform = CGAffineTransformMakeScale(0.01, 0.01);
    } completion:^(BOOL finished) {
        @strongify(self);
        if (self.cancelSelfAcimationEndBlock) {
            self.cancelSelfAcimationEndBlock();
        }
        self.shadowBgView.hidden = YES;
        
        if (self.scrollView.subviews.count > 0) {
            [self.scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        }
        [self removeFromSuperview];
    }];
}

- (void)rotatingAnimationCloseSelf
{
    @weakify(self);
   [UIView animateWithDuration:0.25 animations:^{
       @strongify(self);
       self.backgroundColor = UIColorFromRGB(0x111111, 0);
   }];
    
    UITabBarController *tabbarController = (UITabBarController*)[UIApplication sharedApplication].delegate.window.rootViewController;
    UIView *lastBtnView = tabbarController.tabBar.subviews.lastObject;
    CGFloat lastPointX = lastBtnView.frame.origin.x + lastBtnView.frame.size.width/2;
    
    UIBezierPath *p = [UIBezierPath bezierPath];
    [p moveToPoint:CGPointMake(self.center.x, self.center.y)];
    if ([[LZLanguageManager shareInstance] getLanguageType] == LanguageType_Ar) {
        [p addQuadCurveToPoint:CGPointMake(lastPointX, SCREEN_HEIGHT - 45) controlPoint:CGPointMake(self.center.x - SCREEN_WIDTH/2, self.center.y - SCREEN_HEIGHT/2)];
    }else{
       [p addQuadCurveToPoint:CGPointMake(lastPointX, SCREEN_HEIGHT - 45) controlPoint:CGPointMake(self.center.x +  SCREEN_WIDTH/2, self.center.y - SCREEN_HEIGHT/2)];
    }
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    // 设置动画的路径为心形路径
    animation.path = p.CGPath;

    CABasicAnimation *animation1 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    animation1.fromValue = [NSNumber numberWithFloat:0.6];
    animation1.toValue = [NSNumber numberWithFloat:0.02];
    
    CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation2.fromValue = [NSNumber numberWithFloat:0.0];
    animation2.toValue = [NSNumber numberWithFloat:3 * M_PI]; // 结束时的角度
  
    CAAnimationGroup *group = [CAAnimationGroup animation];
    // 动画选项设定
    group.delegate = self;
    group.duration = .6;
    group.repeatCount = 1;
    group.removedOnCompletion = NO;
    group.fillMode = kCAFillModeForwards;
    // 添加动画
    group.animations = [NSArray arrayWithObjects:animation, animation1,animation2, nil];
    [self.shadowBgView.layer addAnimation:group forKey:@"move-rotate-layer"];
    
    
}


#pragma mark  - animation delegate
/**
 旋转动画结束

 @param theAnimation <#theAnimation description#>
 @param flag <#flag description#>
 */
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
{
    [self.shadowBgView.layer removeAllAnimations];
    self.backgroundColor = UIColorFromRGB(0x111111, 0);
    self.shadowBgView.transform = CGAffineTransformMakeScale(0.01, 0.01);
    self.shadowBgView.hidden = YES;
    if (self.scrollView.subviews.count > 0) {
        [self.scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }
    [self removeFromSuperview];
    
    UITabBarController *tabbarController = (UITabBarController*)[UIApplication sharedApplication].delegate.window.rootViewController;
    NSInteger totleCount = tabbarController.tabBar.subviews.count;
    if (totleCount >= 5) {
        UIView *lastBtnView = tabbarController.tabBar.subviews.lastObject;
        
        if ([NSStringFromClass([lastBtnView class]) isEqualToString:@"UITabBarButton"]) {
            lastBtnView.transform = CGAffineTransformMakeScale(0.6, 0.6);
            
            [UIView animateWithDuration:0.6 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:UIViewAnimationOptionCurveLinear animations:^{
                
                lastBtnView.transform = CGAffineTransformIdentity;
                
            } completion:^(BOOL finished) {
                
                
            }];
        }else{
            lastBtnView = tabbarController.tabBar.subviews[totleCount - 2];
            if ([NSStringFromClass([lastBtnView class]) isEqualToString:@"UITabBarButton"]) {
                lastBtnView.transform = CGAffineTransformMakeScale(0.6, 0.6);
                
                [UIView animateWithDuration:0.6 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:UIViewAnimationOptionCurveLinear animations:^{
                    
                    lastBtnView.transform = CGAffineTransformIdentity;
                    
                } completion:^(BOOL finished) {
                    
                    
                }];
            }
        }
    }
   
}


#pragma mark - scrollview delegate
- (void)grabCouponsAction
{
    if (self.getCouponBlock) {
        self.getCouponBlock();
    }
}

#pragma mark - tap delegate
-(BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch*)touch {
    
    if ([touch.view isKindOfClass:[LZGrabCouponDetailPopView class]]) {
        
        return YES;
    }
    
    return NO;
}

#pragma makr - 
#pragma mark - 控件懒加载
- (UIView *)bgView
{
    if (!_bgView) {
        _bgView = [[UIView alloc] init];
        _bgView.backgroundColor = [UIColor whiteColor];
    }
    
    return _bgView;
}

- (UIView *)shadowBgView
{
    if (!_shadowBgView) {
        _shadowBgView = [[UIView alloc] init];
        _shadowBgView.backgroundColor = [UIColor clearColor];
    }
    
    return _shadowBgView;
}


- (UIImageView *)topImgView
{
    if (!_topImgView) {
        _topImgView = [[UIImageView alloc] init];
        _topImgView.image = [UIImage imageNamed:@"抢券图片"];
    }
    
    return _topImgView;
}

- (UIButton *)cancelBtn
{
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancelBtn setImage:[UIImage imageNamed:@"coupon_pop_close"] forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(cancelSelfWithAnimation) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _cancelBtn;
}

- (LZGrabCouponPopScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[LZGrabCouponPopScrollView alloc] init];
        _scrollView.couponTitleViewForPopDelegate = self;
    }
    
    return _scrollView;
}

- (LZVideoActivityView *)activityView
{
    if (!_activityView) {
        _activityView = [[NSBundle mainBundle] loadNibNamed:@"LZVideoActivityView" owner:self options:nil].lastObject;
    }
    
    [_activityView resetActivity];
    return _activityView;
}

@end
